/**
 * 表格公共model,
 * 后端api， url判断当前路由URL
 */

const grid = (api) => {
    return {
        state: {
            data: [],
            total: 0,
            current: 1,
            size: 20,
            keyword: null,
            fetching: false
        },
        mutations: {
            SET_DATA: (state, { data, total, current, size }) => {
                state.data = data
                state.current = current
                state.total = total
                state.size = size
            },
            SET_FETCHING:(state, payload) => {
                state.fetching = payload
            }
        },
        actions: {
            async fetch({ commit, state }, payload) {
                commit('SET_FETCHING', true)
                const params = {
                    current: state.current,
                    size: state.size,
                    ...payload
                }
                const response = await api.fetch(params)
                if (response && response.httpCode === 200) {
                    const { total, current, size, data} = response;
                    commit('SET_DATA', { data, total, current, size })
                }
                commit('SET_FETCHING', false)
            },
            async save({ commit }, payload) {
                return await api.create(payload)
            },
            async update({ commit }, payload) {
                return await api.update(payload)
            },
            async remove({ commit }, payload) {
                return await api.remove(payload)
            }
        }
    }
}

export default grid;